package zhr.chapter9;

import javax.swing.*;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class KeyEventDemo extends JFrame {
    private JLabel label;
    private boolean isCtr;
    public KeyEventDemo() {
        this.setTitle("键盘事件演示");
        label = new JLabel();
        isCtr = false;
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(label);
        this.setLayout(new FlowLayout());
        this.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                if(e.getModifiersEx() != InputEvent.CTRL_DOWN_MASK){
                    if(isCtr){
                        label.setText("");
                        isCtr = false;
                    }
                }
                label.setText(label.getText() + e.getKeyChar()+" ");
            }
            public void keyPressed(KeyEvent e) {
                if(e.getModifiersEx() == InputEvent.CTRL_DOWN_MASK&&e.getKeyCode() == KeyEvent.VK_Z){
                    isCtr = true;
                    label.setText("Ctrl+Z is Pressed!");
                }
            }
        });
        this.setBounds(100, 100, 600, 300);
        this.setVisible(true);
    }
}
